#!/bin/bash

# 日志文件
LOGFILE="install.log"

# 日志记录函数
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" | tee -a $LOGFILE
}

# 错误处理函数
error_exit() {
    log "Error: $1"
    exit 1
}

# 检查命令是否成功执行
check_command() {
    if [ $? -ne 0 ]; then
        log "Error executing: $1"
    else
        log "Successfully executed: $1"
    fi
}
# 下载 Prometheus
log "开始下载 Prometheus..."
if [ ! -d "prometheus" ]; then
    git clone https://gitee.com/huang_a/prometheus.git
    check_command "git clone https://gitee.com/huang_a/prometheus.git"
    chmod +x -R .
else
    log "Prometheus 已经下载，跳过此步骤."
fi

# 安装 Go 语言
GO_URL="https://gitee.com/huang_a/go_golang.git"
log "开始下载 Go 语言..."
if [ ! -d "go_golang" ]; then
    git clone ${GO_URL} 
    check_command "git clone ${GO_URL}"
    chmod +x -R .
else
    log "Go 安装包已经下载，跳过此步骤."
fi


export PATH=$PWD/go_golang/go/bin:$PATH
log "Go 安装完成."


# 设置 GOROOT 和 GOPATH
log "设置 Go 环境变量..."
go env -w GOROOT=$PWD/go_golang/go
check_command "go env -w GOROOT=$PWD/go_golang/go"
go env -w GOPATH=$PWD/go_golang/golang 
check_command "go env -w GOPATH=$PWD/go_golang/golang "
log "Go 环境变量设置完成."


# 添加 Go 代理
log "添加 Go 代理..."
go env -w GOPROXY=https://goproxy.cn
check_command "go env -w GOPROXY=https://goproxy.cn"

# 安装 goyacc 以解决 make test 报错问题
log "安装 goyacc..."
cd prometheus || error_exit "Failed to change directory to Prometheus."
go install golang.org/x/tools/cmd/goyacc
check_command "go install golang.org/x/tools/cmd/goyacc"
log "goyacc 安装完成."

log "安装NodeJs和npm..."
sudo yum install npm
sudo yum install nodejs
log "检查版本信息"
npm version

log "进入Prometheus目录"
cd prometheus

log "开始构建"
make build 

log "build success"

log "运行"
./prometheus --config.file=documentation/examples/prometheus.yml > prometheus_output.txt 2>&1 &


log "获取Prometheus首页内容"
curl http://localhost:9090
